function [x,objval,LPslack] = solve_pop(N_prefs, N_alphas, alpha_list, start_H)
% Solves QP to determine whether payoff parameters yield equilibrium.

global N N_types obs_shares
% global C_sparse hyp_lim
global muZpH_vec
global LPopts



%% CONSTRAINTS

tic

% A) Lower Bounds = Zero

lb = zeros(N_alphas + 2*N_types,1);

% B) Alphas Add to 1

% Storage:

a = ones(N_prefs,1);
A = sparse([],[], true, N_prefs,N_alphas, N_alphas);

% Populate rows for each preference class:

for H = 1:(length(start_H)-1)
    first = start_H(H);
    last = start_H(H+1)-1;
    %
    A(H,first:last) = true;
end

% Last preference class:

H = N_prefs;
first = start_H(H);
last = N_alphas;
A(H,first:last) = true;

% C) Match Type Shares

% Matrix to get type measures from vector of allocation parameters:

muZpH_mat = sparse(double(alpha_list),1:N_alphas, muZpH_vec, N_types,N_alphas);

% Matrix to set slacks equal to zero:

noslack = speye(2*N_types);

% D) Combine Equality Constraints

a_eq = vertcat(a, obs_shares, zeros(2*N_types,1) );
A_eq = vertcat( [A sparse(N_prefs,2*N_types)], ...
                [muZpH_mat, speye(N_types), -speye(N_types)], ...
				[sparse(2*N_types,N_alphas), noslack] );
				
disp('Make constraints:')
toc



%% LP TO MATCH TYPE SHARES

% Objective - sum of slacks:

addslacks = sparse(N_alphas + (1:2*N_types),1,1);

% Solve LP:

tic
disp('LP problem:')
[startpt,LPslack,LPexitflag] = linprog(addslacks,[],[],A_eq,a_eq,lb,[],[],LPopts);
toc

% Set objval if cannot fit of observed shares:

if LPexitflag < 1
    x = [];
    objval = 1
end



%% QP FOR EQUILIBRIUM

% Only solve QP if prediction matches observed type shares:

if LPexitflag == 1

% Call KNITRO:

[x,objval,QPexitflag] = knitromatlab(@QP_obj, startpt, [],[], A_eq,a_eq, lb,[], [],[],[], 'knitro.opt');

% Values if QP fails to find feasible solution:
% (cannot predict observed type shares)

if QPexitflag == -204 || QPexitflag == -205
    x = [];
    objval = 1
end

end  %  IF LPexitflag == 1



end
